不贪心如何拿Offer
一:股票交易的最大收益:二:换酒问题:三:分发饼干:
一:股票交易的最大收益:
假定你知道某只股票每一天价格的变动。 你最多可以同时持有一只股票。但你可以无限次的交易(买进和卖出均无手续费)。 请设计一个函数,计算你所能获得的最大收益。 根据题意我们可以分析出来,只要是明天比今天涨了,我们就要这个收益。(贪心)
class Solution:
def maxProfit(self , prices ):
res = 0
length = len(prices)
for i in range(1, length):
if prices[i] > prices[i-1]:
res += prices[i] - prices[i-1]
return res
二:换酒问题:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210307140638251.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMzQxNzU3,size_16,color_FFFFFF,t_70)
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
res = 0
count = 0
while(numBottles):
# 1: 喝酒数量增加
res = numBottles + res
# 2: 酒瓶子数量更新
count = count + numBottles
# 3: 酒数量更新
numBottles = count // numExchange
# 4: 剩余酒瓶子数量更新
count = count % numExchange
return res
三:分发饼干:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210307141649666.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMzQxNzU3,size_16,color_FFFFFF,t_70)
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
# 将胃口和饼干尺寸进行排序
g.sort()
s.sort()
# 计算数量
n, m = len(g), len(s)
i = j = count = 0
# 没有到边界就继续走
while i |